package com.singbon.server.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 */
@Slf4j
@Component
public class CustomLoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
  private final String forwardUrl = "www.singbon.coml";
  //  public CustomLoginAuthenticationSuccessHandler(String forwardUrl) {
  //    Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl), () -> {
  //      return "'" + forwardUrl + "' is not a valid forward URL";
  //    });
  //    //    Assert.isTrue(testWsdlConnection(forwardUrl), () -> {
  //    //      return "'" + forwardUrl + "' is can not access";
  //    //    });
  //    this.forwardUrl = forwardUrl;
  //  }
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    // request.getRequestDispatcher(this.forwardUrl).forward(request, response)
    if (checkUrlConnection(forwardUrl)) {
      response.sendRedirect(forwardUrl);
    }
    else {
      response.sendRedirect("Http://www.baidu.com");
    }
  }
  public static boolean checkUrlConnection(String address) {
    boolean isAccess = false;
    try {
      URL urlObj = new URL(address);
      HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
      oc.setUseCaches(false);
      // 设置超时时间
      oc.setConnectTimeout(3000);
      // 请求状态
      int status = oc.getResponseCode();
      System.out.println("status = " + status);
      if (200 == status) {
        // 200是请求地址顺利连通。。
        isAccess = true;
      }
    }
    catch (Exception e) {
      log.warn(e.getMessage());
    }
    return isAccess;
  }
}
